<template>
  <el-upload
    class="avatar-uploader"
    action=""
    :show-file-list="false"
    :before-upload="beforeAvatarUpload"
    :http-request="imageUploadData"
  >
    <img v-if="value" :src="value" class="avatar">
    <i v-else class="el-icon-plus avatar-uploader-icon" />
  </el-upload>
</template>
<script>
import COS from 'cos-js-sdk-v5'
export default {
  props: {
    value: {
      type: String,
      default: ''
    }
  },
  data() {
    return {
    }
  },
  methods: {
    // 头像上传前的操作，校验类型和大小
    beforeAvatarUpload(file) {
      const isJPG = ['image/jpeg', 'image/png', 'image/gif', 'image/bmg'].includes(file.type)
      const isLt2M = file.size / 1024 / 1024 < 5

      if (!isJPG) {
        this.$message.error('上传头像图片只能是 JPG 、PNG、GIF、BMG格式!')
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!')
      }
      return isJPG && isLt2M
    },
    imageUploadData(file) {
      const cos = new COS({
        SecretId: 'AKIDd5KSM5arvmPnxMYWGm5A1d2Dyh5HFzUm',
        SecretKey: 'A5lEXbRBj4ARUKyOegT5TdZGuMaaLsLi'
      })
      cos.putObject({
        Bucket: 'cs-1317190687',
        Region: 'ap-beijing',
        Key: file.file.name,
        StorageClass: 'STANDARD',
        Body: file.file
      }, (err, data) => {
        if (data && data.statusCode === 200) {
          this.$emit('input', `http://${data.Location}`)
        } else {
          this.$message.error(err.Message)
        }
      })
    }
  }
}
</script>
<style>
  .avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }
  .avatar-uploader .el-upload:hover {
    border-color: #409EFF;
  }
  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    line-height: 178px;
    text-align: center;
  }
  .avatar {
    width: 178px;
    height: 178px;
    display: block;
  }
</style>
